package com.csjbot.blackgaga.feature.navigation;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.robot.thirdparty.google.reflect.TypeToken;
import com.bumptech.glide.Glide;
import com.csjbot.blackgaga.R;
import com.csjbot.blackgaga.ai.NaviAI;
import com.csjbot.blackgaga.base.BaseFullScreenActivity;
import com.csjbot.blackgaga.base.BasePresenter;
import com.csjbot.blackgaga.core.RobotManager;
import com.csjbot.blackgaga.feature.navigation.adapter.FileListAdapter;
import com.csjbot.blackgaga.feature.settings.SettingsActivity;
import com.csjbot.blackgaga.global.Constants;
import com.csjbot.blackgaga.localbean.NaviBean;
import com.csjbot.blackgaga.model.tcp.bean.Position;
import com.csjbot.blackgaga.model.tcp.factory.ServerFactory;
import com.csjbot.blackgaga.router.BRouterKey;
import com.csjbot.blackgaga.router.BRouterPath;
import com.csjbot.blackgaga.util.GsonUtils;
import com.csjbot.blackgaga.util.SharedKey;
import com.csjbot.blackgaga.util.SharedPreUtil;
import com.csjbot.blackgaga.util.TimeoutUtil;
import com.csjbot.blackgaga.widget.KeyPointView;
import com.csjbot.coshandler.core.Robot;
import com.csjbot.coshandler.listener.OnNaviSearchListener;
import com.csjbot.coshandler.listener.OnPositionListener;
import com.csjbot.coshandler.listener.OnSpeakListener;
import com.csjbot.coshandler.log.Csjlogger;
import com.iflytek.cloud.SpeechError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by jingwc on 2017/9/21.
 * Powered by xiasuhuei321
 * <p>
 * 友好的提示：先摸清楚所有的流程，各种延时可能会看的你懵逼，
 * 但是没办法，应用层协议没有使用现成的，只能自己加上计时器了。
 */

@Route(path = BRouterPath.NAVI_MAIN)
public class NaviActivity extends BaseFullScreenActivity implements NaviContract.View {

    NaviContract.Presenter mPresenter;

    NaviAI mAI;

    // 如果为 true 说明是说了一个没有的点
    @Autowired(name = BRouterKey.NO_POINT_GUIDE)
    boolean isFromAI = false;

    // 导航点数据
    public List<NaviBean> naviBeanList = null;
    // 这个集合保存的是需要导航的店的信息
    public List<NaviBean> workList = new ArrayList<>();
    boolean hasData = false;

    public static final int GUIDE_AWAIT = 10004;

    public static final int GUIDE_ALL = 10086;
    public static final int GUIDE_SINGLE = 10087;
    public static final int GUIDE_BACK = 10088;
    public static final int GUIDE_DEFAULT = -1;
    public volatile int workType = GUIDE_DEFAULT;

    public static final int MSG_TIMEOUT = -10086;
    // 超时消息下发超时
    public static final int MSG_TIMEOUTMSG_TIMEOUT = -10087;

    private boolean isYinbinPoint = true;

    private volatile Runnable currentRunnable;
    private int nodeCount = 0;
    private int guideClickCount = 0;
    private TimeoutUtil naviTimeout = new TimeoutUtil();

    // u盘路径
    public static final String USB_PATH = "/mnt/usb_storage";
    // 导航数据存放路径
    public static String NAV_DATA_PATH = Environment.getExternalStorageDirectory() + File.separator + "blackgaga"
            + File.separator + "nav_data";

    private Dialog mapDialog = null;


    public static String[] suffixs = {
            ".jpg", ".jpeg", ".png"
    };

    @BindView(R.id.iv_map)
    ImageView iv_map;
    @BindView(R.id.rl_map)
    RelativeLayout rl_map;
    @BindView(R.id.tv_point_name)
    TextView tv_point_name;
    @BindView(R.id.tv_desc)
    TextView tv_desc;
    @BindView(R.id.rl_text_root)
    RelativeLayout rl_text_root;
    @BindView(R.id.rl_guide)
    RelativeLayout rl_guide;
    @BindView(R.id.tv_guide)
    TextView tv_guide;
    @BindView(R.id.bt_start_guide)
    Button bt_start_guide;
    @BindView(R.id.iv_icon)
    ImageView iv_icon;

    private FileListAdapter adapter;
    private ListView lv_file_list;
    private AlertDialog dialog;

    private boolean hasMap = false;
    public TaskStatusManager guideAllTask;
    public TaskStatusManager guideSingle;
    public boolean isAITalk = false;
    private ArmLooper armLooper = new ArmLooper();

    @Override
    protected BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_navi;
    }

    @Override
    public void afterViewCreated(Bundle savedInstanceState) {
        super.afterViewCreated(savedInstanceState);
        guideAllTask = new TaskStatusManager();
        guideSingle = new TaskStatusManager();
        openNoNetworkDialog = false;

        IntentFilter filter = new IntentFilter(Constants.WAKE_UP);
        registerReceiver(receiver, filter);

        IntentFilter aFilter = new IntentFilter("com.example.BROADCAST");
        registerReceiver(aReceiver, aFilter);
    }

    private BroadcastReceiver aReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (workType == GUIDE_ALL) {
                // 如果正在进行导览
                if (guideAllTask.workStatus == TaskStatusManager.START) {
                    NaviActivity.this.finish();
                }
            }

            if (workType == GUIDE_SINGLE) {
                NaviActivity.this.finish();
            }
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (workType == GUIDE_ALL) {
                // 如果正在进行导览
                if (guideAllTask.workStatus == TaskStatusManager.START) {
                    guide();
                }
            }

            if (workType == GUIDE_SINGLE) {
                if (guideSingle.workStatus == TaskStatusManager.START) {
                    guideImm();
                }
            }

//            if(workType == GUIDE_BACK){
//                handler.post(()->{
//                    String json = SharedPreUtil.getString(SharedKey.YINGBIN_NAME, SharedKey.YINGBIN_KEY);
//                    List<Position> positionList = GsonUtils.jsonToObject(json, new TypeToken<List<Position>>() {
//                    }.getType());
//
//                    workState = GUIDE_BACK;
//                    workType = GUIDE_BACK;
//
//                    handler.postDelayed(()->{
//                        Position position = positionList.get(0);
//                        RobotManager.getInstance().robot.reqProxy.navi(position.toJson());
//                        Csjlogger.debug(json);
//                    },2000);
//                });
//            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        Robot.getInstance().setOnNaviSearchListener(searchListener);
        // 刷新一下全局导航的数据

        RobotManager.getInstance().addListener(positionListener);
        if (!SharedPreUtil.getBoolean(SharedKey.ISLOADMAP, SharedKey.ISLOADMAP)) {
            Toast.makeText(this, R.string.plz_restore_map_tip, Toast.LENGTH_LONG).show();
        }
        String json = SharedPreUtil.getString(SharedKey.NAVI_NAME, SharedKey.NAVI_KEY);
        if (TextUtils.isEmpty(json)) {
            // 获取的 json 为空
            String mapPath = SharedPreUtil.getString(SharedKey.NAVI_NAME, SharedKey.MAP_PATH);
            // 获取不到地图，提示用户添加地图
            if (TextUtils.isEmpty(mapPath)) {
                Csjlogger.debug("Navi:没有地图");
            } else {
                // 有地图，但是没设置
                Csjlogger.debug("Navi:地图路径：" + mapPath);
                hasMap = true;
                Glide.with(this).load(mapPath).into(iv_map);
            }
        } else {
            Csjlogger.debug("Navi:导航地图数据\n" + json);

            String mapPath = SharedPreUtil.getString(SharedKey.NAVI_NAME, SharedKey.MAP_PATH);
            naviBeanList = GsonUtils.jsonToObject(json, new TypeToken<List<NaviBean>>() {
            }.getType());

            if (!TextUtils.isEmpty(mapPath)) {
                Csjlogger.debug("Navi:地图路径：" + mapPath);
                Glide.with(this).load(mapPath).into(iv_map);
                hasMap = true;
            }

            if (naviBeanList == null || naviBeanList.size() <= 0) {
                Csjlogger.debug("Navi:没有数据");
            } else {
                hasData = true;
                Csjlogger.debug("Navi:获取到关键点数量：" + naviBeanList.size());
                initMap(naviBeanList);
            }
        }

        NaviAction.getInstance().initData();
    }

    /**
     * 初始化地图，将点绘制到地图上
     */
    private void initMap(List<NaviBean> naviList) {
        int count = rl_map.getChildCount() - 1;
        if (count >= 2) {
            while (count > 1) {
                rl_map.removeViewAt(count);
                count--;
            }
        }

        for (NaviBean n : naviList) {
            addPointView(n);
        }
    }

    private NaviBean currentSelect = null;

    /**
     * 当用户点击后，展示地图信息
     */
    public void showInfo(NaviBean n) {
        currentSelect = n;
        rl_text_root.setVisibility(View.VISIBLE);
        tv_point_name.setText(n.getName());
        tv_desc.setText(n.getDescription());
    }

    public void hideInfo() {
        rl_text_root.setVisibility(View.GONE);
        tv_point_name.setText(null);
        tv_desc.setText(null);
    }

    /**
     * 在有数据的情况下添加导引点到地图上
     */
    private void addPointView(NaviBean naviBean) {
        KeyPointView keyPointView = new KeyPointView(this);

        keyPointView.setName(naviBean.getName());
        keyPointView.layout(naviBean.left, naviBean.top, naviBean.right, naviBean.bottom);
        keyPointView.setTranslationX(naviBean.getTranslationX());
        keyPointView.setTranslationY(naviBean.getTranslationY());

        Csjlogger.debug("Navi:left=" + naviBean.left + " top=" + naviBean.top + " right=" + naviBean.right + " bottom=" + naviBean.bottom);

        keyPointView.setName(naviBean.getName());
        keyPointView.setOnClickListener(v -> {
            showInfo(naviBean);
        });

        rl_map.addView(keyPointView);
    }

    @Override
    public void init() {
        super.init();
        mPresenter = new NaviPresenter();
        mPresenter.initView(this);

        getTitleView().setBackVisibility(View.VISIBLE);
        if (!isFromAI) {
            String msg = getString(R.string.navi_init_text);
            speak(msg, true);
        } else {
            speak(R.string.navi_hint_ai, true);
        }

        mAI = NaviAI.newInstance();
        mAI.initAI(this);
    }

    @Override
    protected boolean onSpeechMessage(String text, String answerText) {
        if (super.onSpeechMessage(text, answerText)) {
            return false;
        }
        NaviAI.Intent intent = mAI.getIntent(text);
        if (intent != null) {
            mAI.handleIntent(intent);
        } else {
//            prattle(answerText);
        }
        return true;
    }


    @Override
    public boolean isOpenChat() {
        return true;
    }

    @Override
    public boolean isOpenTitle() {
        return true;
    }

    boolean resumeFlag = false;
    long clickTime = 0;

    // 一键导引
    @OnClick(R.id.tv_guide)
    public void guide() {
        // 限制点击频率
        guideClickCount++;
        long lastTime = System.currentTimeMillis() - clickTime;
        clickTime = System.currentTimeMillis();
        if (lastTime >= 3000) {
            guideClickCount = 0;
            Csjlogger.debug("上一次点击距现在时间超过3s");
        }

        if (guideClickCount >= 1) {
            Toast.makeText(context, R.string.click_too_more, Toast.LENGTH_SHORT).show();
            tv_guide.setEnabled(false);
            handler.postDelayed(() -> {
                guideClickCount = 0;
                tv_guide.setEnabled(true);
            }, 3000);
            return;
        }
        // 获取一键导览数据
        String json = SharedPreUtil.getString(SharedKey.GUIDE_NAME, SharedKey.GUIDE_KEY);
        workList = GsonUtils.jsonToObject(json, new TypeToken<List<NaviBean>>() {
        }.getType());

        // 没有数据，跳转到设置界面
        if (workList == null || workList.size() == 0) {
            speak(R.string.set_none_navi_guide, new OnSpeakListener() {
                @Override
                public void onSpeakBegin() {

                }

                @Override
                public void onCompleted(SpeechError speechError) {
                    Intent intent = new Intent(NaviActivity.this, SettingsActivity.class);
                    intent.putExtra(Constants.JUMP_ACTIVITY_NAME, "com.csjbot.blackgaga.feature.navigation.setting.NaviSettingActivity");
                    intent.putExtra(Constants.GUIDE_ALL, true);
                    startActivity(intent);
                }
            }, true);
            return;
        }

        // 工作种类判断，正在单项导览就无法进行
        if (guideSingle.workStatus == TaskStatusManager.START) {
            speak(R.string.working_ing, true);
            return;
        } else if (workType == GUIDE_BACK) {
            speak(R.string.working_ing, true);
            return;
        }

        workType = GUIDE_ALL;

        switch (guideAllTask.workStatus) {
            case TaskStatusManager.START:
                guideAllTask.pause();
                pauseGuideAll();
                break;

            case TaskStatusManager.PAUSE:
                // 从暂停状态恢复
                guideAllTask.resume();
                resumeGuideAll();
                break;

            case TaskStatusManager.AWAIT:
                // 开始工作
//                ServerFactory.getActionInstance().nodAction();
                guideAllTask.start();
                startGuideAll();
                break;

            default:
                break;
        }

    }

    /**
     * 开始一键导览
     */
    public void startGuideAll() {
        if (guideSingle.workStatus == TaskStatusManager.START) {
            speak(R.string.working_ing, true);
            Csjlogger.debug("Navi:正在执行单步导览，一键导览无法进行");
            // 进入这个方法之前已经将这个任务的标识置为了开始，所以重置一下
            guideAllTask.init();
            return;
        }

        // 开始超时计时
        startGuideAllCount();
        tv_guide.setEnabled(false);
        startingGuideAll();

        speak(getString(R.string.i_go), new OnSpeakListener() {
            @Override
            public void onSpeakBegin() {

            }

            @Override
            public void onCompleted(SpeechError speechError) {
                runGuideAllTask(workList);
            }
        }, true);

    }

    /**
     * 暂停一键导览
     */
    public void pauseGuideAll() {
        tv_guide.setEnabled(false);
        if (workList != null) {
            Csjlogger.debug("size: " + workList.size() + " execount: " + executeTaskCount);
        }
        if (currentRunnable != null && workList != null &&
                executeTaskCount >= workList.size()) {
            handler.removeCallbacks(currentRunnable);
            Csjlogger.debug("取消延时回调");
        } else {
            Csjlogger.debug("为什么不走？？？");
        }

        cancelTask();
    }

    /**
     * 恢复一键导览
     */
    public void resumeGuideAll() {
        guideAllTask.resume();
        tv_guide.setText(R.string.stop_guide);
        iv_icon.setBackgroundResource(R.drawable.btn_stop_icon);
        speak(R.string.i_go, true);
        runGuideAllTask(workList);
    }

    private void runGuideAllTask(List<NaviBean> naviBeanList) {
        if (naviBeanList == null) {
            Csjlogger.debug("Navi:要执行的任务为空?");
            return;
        }
        if (executeTaskCount >= naviBeanList.size()) {
            Csjlogger.debug("Navi:导引所有任务点已经走完，导引结束");
            tv_guide.setText(R.string.guide);
            iv_icon.setBackgroundResource(R.drawable.btn_start_icon);
            runOnUiThread(() -> {
                if (guideAllTask.workStatus == TaskStatusManager.START) {
                    currentRunnable = () -> speak(getString(R.string.navi_finish), new OnSpeakListener() {
                        @Override
                        public void onSpeakBegin() {

                        }

                        @Override
                        public void onCompleted(SpeechError speechError) {
                            backWelCome();
                            hideInfo();
                            NaviActivity.this.executeTaskCount = 0;
                        }
                    }, true);
                }
                handler.postDelayed(currentRunnable, 1000);
            });
        } else {
            NaviBean naviBean = naviBeanList.get(executeTaskCount);
            showInfo(naviBean);
            RobotManager.getInstance().robot.reqProxy.navi(naviBean.toJson());
            Csjlogger.debug("Navi:走点消息已发送：" + naviBean.toJson());
        }
    }

    public void guideAllMoveResult(boolean isSuccess) {
//        if (!isSuccess) {
//            Csjlogger.debug("Navi:走点失败，重新开始走点");
//            runGuideAllTask(workList);
//            return;
//        }
        if (isSuccess) {
            tv_guide.setEnabled(false);
            currentRunnable = null;
            NaviBean naviBean = workList.get(executeTaskCount);
            executeTaskCount++;
            Csjlogger.debug("Navi:地点名称：" + naviBean.getName() + " 描述：" + naviBean.getDescription());
            runOnUiThread(() -> speak(naviBean.getName() + getString(R.string.arrived), new OnSpeakListener() {
                @Override
                public void onSpeakBegin() {

                }

                @Override
                public void onCompleted(SpeechError speechError) {
                    handler.postDelayed(() -> speak(naviBean.getDescription(), new OnSpeakListener() {
                        @Override
                        public void onSpeakBegin() {

                        }

                        @Override
                        public void onCompleted(SpeechError speechError) {
                            currentRunnable = () -> {
                                runGuideAllTask(workList);
                                tv_guide.setEnabled(true);
                            };
                            handler.postDelayed(currentRunnable, 2000);
                        }
                    }, true), 1000);
                }
            }, true));
        } else {
            tv_guide.setEnabled(false);
            runOnUiThread(() -> handler.postDelayed(() -> {
                Toast.makeText(context, "路径规划失败，即将前往下个点", Toast.LENGTH_SHORT).show();
                executeTaskCount++;
                tv_guide.setEnabled(true);
                runGuideAllTask(workList);
            }, 1000));
        }
    }

    private void pauseGuideSingle() {
        cancelTask();
    }

    private void resumeGuideSingle() {
        startGuideSingle();
    }

    private void initGuideAll() {
        tv_guide.setText(R.string.guide);
        iv_icon.setBackgroundResource(R.drawable.btn_start_icon);
        tv_guide.setEnabled(true);
    }

    private void initGuideSingle() {
        bt_start_guide.setText(R.string.go_imm);
        hideInfo();
        bt_start_guide.setEnabled(true);
    }

    /**
     * 单项导览移动结果回调
     */
    public void guideSingleMoveResult(NaviBean naviBean, boolean isSuccess) {
        // 已经结束了
        Csjlogger.debug("Navi:单项导航");
        if (!isSuccess) {
            guideImm();
            return;
        }

        hideInfo();
        if (!isFromAI) singleBack();
        else {
            speak(currentSelect.getName() + getString(R.string.arrived) + getString(R.string.back_help_find));
            // TODO: 2017/12/12 跳转到评价界面
        }
    }

    private void singleBack() {
        runOnUiThread(() -> speak(currentSelect.getName() + getString(R.string.arrived), new OnSpeakListener() {
            @Override
            public void onSpeakBegin() {

            }

            @Override
            public void onCompleted(SpeechError speechError) {
                handler.postDelayed(() -> speak(currentSelect.getDescription(), new OnSpeakListener() {
                    @Override
                    public void onSpeakBegin() {

                    }

                    @Override
                    public void onCompleted(SpeechError speechError) {
                        handler.postDelayed(() -> {
                            speak(R.string.navi_finish);
                            bt_start_guide.setText(R.string.go_imm);
                            backWelCome();
                        }, 3000);
                    }
                }, true), 1000);
            }
        }, true));
    }


    /**
     * 分发移动结果
     */
    OnPositionListener positionListener = new OnPositionListener() {
        @Override
        public void positionInfo(String json) {

        }

        @Override
        public void moveResult(String json) {
            runOnUiThread(() -> {
                Csjlogger.debug("进入了移动结果回调，返回json：" + json);
                boolean isSuccess = false;
                try {
                    JSONObject jsonObj = new JSONObject(json);
                    int error_code = jsonObj.optInt("error_code");

                    if (error_code != 0) {
                        Csjlogger.debug("Navi:走点失败");
                        isSuccess = false;
                    } else {
                        isSuccess = true;
                    }

                    if (error_code == 20006) {
//                        Csjlogger.debug("发送过于频繁");
//                        if (workType == GUIDE_BACK) backYinbin();
                    }
                } catch (Exception e) {
                    Csjlogger.error(e);
                    e.printStackTrace();
                }

                if (workType == GUIDE_ALL) {
                    Csjlogger.debug("Navi:开始分发移动结果");
                    armLooper.stopLooper();
                    guideAllMoveResult(isSuccess);
                    handler.removeMessages(MSG_TIMEOUT);
                    handler.removeMessages(MSG_TIMEOUTMSG_TIMEOUT);
                } else if (workType == GUIDE_SINGLE) {
                    armLooper.stopLooper();
                    guideSingleMoveResult(currentSelect, isSuccess);
                    // 开启到点超时计时
                    handler.removeMessages(MSG_TIMEOUT);
                    handler.removeMessages(MSG_TIMEOUTMSG_TIMEOUT);
                } else if (workType == GUIDE_BACK) {
                    handler.removeMessages(MSG_TIMEOUT);
                    handler.removeMessages(MSG_TIMEOUTMSG_TIMEOUT);
                    if (!isSuccess) {
                        backWelCome();
                    } else {
                        armLooper.stopLooper();
                        workType = GUIDE_DEFAULT;
                        speak(R.string.back_already, true);
                        // 重置标识
                        currentSelect = null;
                        executeTaskCount = 0;
                        guideSingle.init();
                        guideAllTask.init();
                        initGuideSingle();
                        initGuideAll();
                        nodeCount = 0;
                    }
                }
            });
        }

        @Override
        public void moveToResult(String json) {
            Csjlogger.debug("消息下发成功");
            runOnUiThread(() -> {
                // 表示消息下发成功
                if (workType == GUIDE_ALL) {
                    isPush = true;
                    armLooper.startLooper();
                    if (executeTaskCount == 0 && nodeCount == 0) {
                        ServerFactory.getActionInstance().nodAction();
                        nodeCount++;
                    }
                    cancelGuideAllTimer();
                    handler.sendEmptyMessageDelayed(MSG_TIMEOUT, 20000);
                } else if (workType == GUIDE_SINGLE) {
                    isGuideSinglePush = true;
                    isPush = true;
                    armLooper.startLooper();
                    ServerFactory.getActionInstance().nodAction();
                    cancelGuideSingle();
                    handler.sendEmptyMessageDelayed(MSG_TIMEOUT, 20000);
//                bt_start_guide.setClickable(false);
                } else if (workType == GUIDE_BACK) {
                    isPush = true;
                    armLooper.startLooper();
                    // 返回迎宾点消息已经下发，重置一键导览与单步导览状态
                    initGuideAll();
                    initGuideSingle();
                }
            });
        }

        @Override
        public void cancelResult(String json) {
            try {
                JSONObject jo = new JSONObject(json);
                int error_code = jo.optInt("error_code");
                if (error_code == 0) {
                    runOnUiThread(() -> {
                        // 取消任务成功
                        Csjlogger.debug("取消任务成功");
                        handler.removeMessages(CANCEL_TASK);
                        if (workType == GUIDE_BACK) {
                            backWelcome.setEnabled(true);
                        }

                        if (workType == GUIDE_SINGLE) {
                            speak(R.string.current_cancel, true);
                            bt_start_guide.setText(R.string.go_imm);
                            bt_start_guide.setEnabled(true);
                            guideSingle.pause();
                            armLooper.stopLooper();
                        }

                        if (workType == GUIDE_ALL) {
                            guideAllTask.pause();
                            tv_guide.setEnabled(true);
                            tv_guide.setText(R.string.guide);
                            armLooper.stopLooper();
                            iv_icon.setBackgroundResource(R.drawable.btn_start_icon);
                            speak(R.string.pause_guide_all_task, true);
                        }
                    });
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @BindView(R.id.rl_back_welcome)
    View backWelcome;

    /**
     * 返回迎宾点
     */
    @OnClick(R.id.rl_back_welcome)
    public void backWelCome() {
        String json = SharedPreUtil.getString(SharedKey.YINGBIN_NAME, SharedKey.YINGBIN_KEY);
        List<Position> positionList = GsonUtils.jsonToObject(json, new TypeToken<List<Position>>() {
        }.getType());

        if (positionList == null || positionList.size() <= 0) {
            Toast.makeText(context, R.string.no_yinbin, Toast.LENGTH_SHORT).show();
            Csjlogger.debug("Navi:尚未设置迎宾点");
            return;
        }

        if (workType == GUIDE_BACK) {
            return;
        }
        stopSpeak();
        backWelcome.setEnabled(false);
        cancelTask();
        if (currentRunnable != null) {
            handler.removeCallbacks(currentRunnable);
        }
        executeTaskCount = 0;
        workType = GUIDE_BACK;
        Position position = positionList.get(0);
        handler.postDelayed(() -> {
            RobotManager.getInstance().robot.reqProxy.navi(position.toJson());
            Csjlogger.debug(json);
        }, 1000);
    }

    /**
     * 立即前往，单项导航
     */
    @OnClick(R.id.bt_start_guide)
    public void guideImm() {
        if (guideAllTask.workStatus == TaskStatusManager.START) {
            speak(R.string.working_ing, true);
            Csjlogger.debug("Navi:正在执行一键导览，单步导览无法进行");
            return;
        } else if (workType == GUIDE_BACK) {
            speak(R.string.working_ing, true);
            Csjlogger.debug("Navi:正在执行一键导览，单步导览无法进行");
            return;
        }

        workType = GUIDE_SINGLE;

        Csjlogger.debug("Navi:立即前往");
        switch (guideSingle.workStatus) {
            case TaskStatusManager.AWAIT:
                guideSingle.start();
                startGuideSingle();
                break;

            case TaskStatusManager.PAUSE:
                guideSingle.resume();
                resumeGuideSingle();
                break;

            case TaskStatusManager.START:
                guideSingle.pause();
                pauseGuideSingle();
                break;

        }
    }

    private void startGuideSingle() {
        if (currentSelect == null) {
            speak(getString(R.string.no_select_point), true);
        } else {
            speak(R.string.go_with_me, true);
            startGuideSingleCount();
            startingGuideSingle();
            RobotManager.getInstance().robot.reqProxy.navi(currentSelect.toJson());
        }
    }


    /**
     * 管理地图
     */
    @OnClick(R.id.iv_map_manage)
    public void manageMap() {
//        addMapGuide();
        Intent intent = new Intent(this, SettingsActivity.class);
        intent.putExtra(Constants.JUMP_ACTIVITY_NAME, "com.csjbot.blackgaga.feature.navigation.setting.NaviSettingActivity");
        startActivity(intent);
    }

    volatile int executeTaskCount = 0;
    boolean cancelFlag = false;
    boolean inRunning = false;

    private static final int CANCEL_TASK = 11111111;

    /**
     * 取消任务
     */
    public void cancelTask() {
        handler.sendEmptyMessageDelayed(CANCEL_TASK, 5000);
        RobotManager.getInstance().robot.reqProxy.cancelNavi();
        inRunning = false;
        cancelFlag = true;
        naviTimeout.cancel();
        handler.removeMessages(MSG_TIMEOUT);
        handler.removeMessages(MSG_TIMEOUTMSG_TIMEOUT);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        unregisterReceiver(aReceiver);
        Robot.getInstance().setOnNaviSearchListener(null);
        Robot.getInstance().setPositionListener(null);
        cancelTask();
        handler.removeCallbacksAndMessages(null);
        armLooper.stopLooper();
    }

    /******************** 超时计时代码 **********************/

    CountDownTimer guideAllTimer;
    volatile boolean isPush = false;

    private void startGuideAllCount() {
        guideAllTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                // 如果消息没有下发到
                if (!isPush) {
                    Csjlogger.debug("Navi:一键导览消息下发超时");
                    Toast.makeText(context, R.string.start_failed_check, Toast.LENGTH_SHORT).show();
                    initGuideAll();
                    // 重置标识
                    guideAllTask.workStatus = TaskStatusManager.AWAIT;
                    workType = GUIDE_DEFAULT;
                }
            }
        };

        guideAllTimer.start();
    }

    CountDownTimer guideSingleTimer;
    volatile boolean isGuideSinglePush = false;

    private void cancelGuideAllTimer() {
        if (guideAllTimer != null) {
            guideAllTimer.cancel();
        }
        inRunningGuideAll();
    }

    private void startGuideSingleCount() {

        guideSingleTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (!isGuideSinglePush) {
                    Csjlogger.debug("Navi:单项导览消息下发超时");
                    Toast.makeText(context, R.string.start_failed_check, Toast.LENGTH_SHORT).show();
                    initGuideSingle();
                    // 重置标识
                    guideSingle.workStatus = TaskStatusManager.AWAIT;
                    workType = GUIDE_DEFAULT;
                }
            }
        };

        guideSingleTimer.start();
    }

    private void cancelGuideSingle() {
        if (guideSingleTimer != null) {
            guideSingleTimer.cancel();
        }
        inRunningGuideSingle();
    }

    /**
     * 切换到一键导引按钮启动中状态
     */
    public void startingGuideAll() {
        tv_guide.setText(R.string.start_guide_all);
        tv_guide.setEnabled(false);
//        tv_guide.setTextColor(Color.RED);
    }

    /**
     * 切换到一键导引运行中状态
     */
    public void inRunningGuideAll() {
        tv_guide.setEnabled(true);
        tv_guide.setText(R.string.stop_guide);
        iv_icon.setBackgroundResource(R.drawable.btn_stop_icon);
        guideAllTask.start();
    }

    /**
     * 切换到单步导览启动中状态
     */
    public void startingGuideSingle() {
        bt_start_guide.setText(R.string.starting_single);
        bt_start_guide.setEnabled(false);
    }

    /**
     * 切换到奥单步导览运行中状态
     */
    public void inRunningGuideSingle() {
        bt_start_guide.setEnabled(true);
        guideSingle.start();
        bt_start_guide.setText(R.string.cancel);
    }

    public void backYinbin() {
        String j = SharedPreUtil.getString(SharedKey.YINGBIN_NAME, SharedKey.YINGBIN_KEY);
        List<Position> positionList = GsonUtils.jsonToObject(j, new TypeToken<List<Position>>() {
        }.getType());

        RobotManager.getInstance().robot.reqProxy.navi(positionList.get(0).toJson());
        Csjlogger.debug(j);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CANCEL_TASK:
                    Csjlogger.debug("消息还是发到这了？");
                    if (workType == GUIDE_BACK) {
                        backWelcome.setEnabled(true);
                    }

                    if (workType == GUIDE_ALL) {
                        inRunningGuideAll();
                    }

                    if (workType == GUIDE_SINGLE) {
                        inRunningGuideSingle();
                    }

                    Toast.makeText(context, R.string.cancel_failed, Toast.LENGTH_SHORT).show();
                    break;

                case MSG_TIMEOUT:
                    Csjlogger.debug("超时，查询导航状态");
                    listener.timeOut();
                    break;
                case MSG_TIMEOUTMSG_TIMEOUT:
                    Csjlogger.debug("超时消息下发超时");
                    listener.timeOut();
                    break;
                default:

                    break;
            }
        }
    };

    TimeoutUtil.TimeoutListener listener = () -> {
        Robot.getInstance().reqProxy.search();
        handler.sendEmptyMessageDelayed(MSG_TIMEOUTMSG_TIMEOUT, 5000);
    };

    OnNaviSearchListener searchListener = json -> runOnUiThread(() -> {
        handler.removeMessages(MSG_TIMEOUT);
        handler.removeMessages(MSG_TIMEOUTMSG_TIMEOUT);
        try {
            JSONObject jo = new JSONObject(json);
            int state = jo.optInt("state");
            if (state == 0) {
                runGuideAllTask(workList);
                Csjlogger.debug("Navi：state==0，尝试重新走点");
            } else if (state == 1) {
//                naviTimeout.start(20000, listener);
                handler.sendEmptyMessageDelayed(MSG_TIMEOUT, 20000);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    });

}